var cluster = require('cluster');

import Express from 'express';

import compression from 'compression';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import path from 'path';
import IntlWrapper from '../client/modules/Intl/IntlWrapper';

// Webpack Requirements
import webpack from 'webpack';
import config from '../webpack.config.dev';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';

// Initialize the Express App
const app = new Express();

// Set Development modes checks
const isDevMode = process.env.NODE_ENV === 'development' || false;
const isProdMode = process.env.NODE_ENV === 'production' || false;

// Run Webpack dev server in development mode
if (isDevMode) {
  const compiler = webpack(config);
  app.use(
    webpackDevMiddleware(compiler, {
      noInfo: true,
      publicPath: config.output.publicPath
    })
  );
  app.use(webpackHotMiddleware(compiler));
}

// React And Redux Setup
import { configureStore } from '../client/store';
import { Provider } from 'react-redux';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import Helmet from 'react-helmet';

// Import required modules
import routes from '../client/routes';
import { fetchComponentData } from './util/fetchData';
import posts from './routes/post.routes';
import dummyData from './dummyData';
import serverConfig from './config';

// Set native promises as mongoose promise
mongoose.Promise = global.Promise;
//
// // MongoDB Connection
// mongoose.connect(serverConfig.mongoURL, (error) => {
//   if (error) {
//     console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console
//     throw error;
//   }
//
//   // feed some dummy data in DB.
//   dummyData();
// });

// Apply body Parser and server public assets and routes
app.use(compression());
app.use(bodyParser());
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }));
app.use(Express.static(path.resolve(__dirname, '../public')));
app.use('/api', posts);

// var final = require('./applications/final/app');
// app.use('/final', final);

var helloworld = require('./applications/helloworld/app');
app.use('/helloworld', helloworld);

var shitu = require('./applications/Wi-Fi_station_weixin/shitu_back_end/tencentyoutuyun/sample');
app.use('/shitu', shitu);

var login = require('./applications/login/login');
app.use('/login', login);

var hackson = require('./applications/hackson/app');
app.use('/hackson', hackson);

var mark = require('./applications/mark/app');
app.use('/mark', mark);

var team = require('./applications/team/app');
app.use('/team', team);

var minihabit = require('./applications/minihabit/app');
app.use('/minihabit', minihabit);

// var canvas = require("./applications/canvas/app")
// app.use("/canvas", minihabit);

// 定制 404 页面
app.use(function(req, res) {
  res.type('text/plain');
  res.status(404);
  res.send('404 - Not Found');
});

// 定制 500 页面
app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.type('text/plain');
  res.status(500);
  res.send('500 - Server Error');
});

// // Render Initial HTML
// const renderFullPage = (html, initialState) => {
//   const head = Helmet.rewind();
//
//   // Import Manifests
//   const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets);
//   const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets);
//
//   return `
//     <!doctype html>
//     <html>
//       <head>
//         ${head.base.toString()}
//         ${head.title.toString()}
//         ${head.meta.toString()}
//         ${head.link.toString()}
//         ${head.script.toString()}
//
//         ${isProdMode ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''}
//         <link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'/>
//         <link rel="shortcut icon" href="http://res.cloudinary.com/hashnode/image/upload/v1455629445/static_imgs/mern/mern-favicon-circle-fill.png" type="image/png" />
//       </head>
//       <body>
//         <div id="root">${html}</div>
//         <script>
//           window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
//           ${isProdMode ?
//           `//<![CDATA[
//           window.webpackManifest = ${JSON.stringify(chunkManifest)};
//           //]]>` : ''}
//         </script>
//         <script src='${isProdMode ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script>
//         <script src='${isProdMode ? assetsManifest['/app.js'] : '/app.js'}'></script>
//       </body>
//     </html>
//   `;
// };
//
// const renderError = err => {
//   const softTab = '&#32;&#32;&#32;&#32;';
//   const errTrace = isProdMode ?
//     `:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : '';
//   return renderFullPage(`Server Error${errTrace}`, {});
// };
//
// // Server Side Rendering based on routes matched by React-router.
// app.use((req, res, next) => {
//   match({ routes, location: req.url }, (err, redirectLocation, renderProps) => {
//     if (err) {
//       return res.status(500).end(renderError(err));
//     }
//
//     if (redirectLocation) {
//       return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
//     }
//
//     if (!renderProps) {
//       return next();
//     }
//
//     const store = configureStore();
//
//     return fetchComponentData(store, renderProps.components, renderProps.params)
//       .then(() => {
//         const initialView = renderToString(
//           <Provider store={store}>
//             <IntlWrapper>
//               <RouterContext {...renderProps} />
//             </IntlWrapper>
//           </Provider>
//         );
//         const finalState = store.getState();
//
//         res
//           .set('Content-Type', 'text/html')
//           .status(200)
//           .end(renderFullPage(initialView, finalState));
//       })
//       .catch((error) => next(error));
//   });
// });

//
// if (cluster.isMaster) {
//   require('os').cpus().forEach(function () {
//     startWorker();
//   });
// // 记录所有断开的工作线程。如果工作线程断开了，它应该退出 // 因此我们可以等待 exit 事件然后繁衍一个新工作线程来代替它
//   cluster.on('disconnect', function (worker) {
//     console.log('CLUSTER: Worker %d disconnected from the cluster.',
//       worker.id);
//   })
//   ;
// // 当有工作线程死掉(退出)时，创建一个工作线程代替它
//   cluster.on('exit', function (worker, code, signal) {
//     console.log('CLUSTER: Worker %d died with exit code %d (%s)',
//       worker.id, code, signal);
//     startWorker();
//   })
//   ;
// } else {
// // 在这个工作线程上启动我们的应用服务器，参见 meadowlark.js
// // start app
app.listen(serverConfig.port, error => {
  if (!error) {
    console.log(
      `MERN is running on port: ${serverConfig.port}! Build something amazing!`
    ); // eslint-disable-line
  }
});
// }

function startWorker() {
  var worker = cluster.fork();
  console.log('CLUSTER: Worker %d started', worker.id);
}

export default app;
